import React, { useState, useEffect } from "react";
import { message, Table, Tree, Tag, Spin } from "antd";
import styles from "./index.less";
import {
  get4AChildOrgByParentOrgId,
  get4APositionByOrgId
} from "../../../../services/acceptGroup";

const { TreeNode } = Tree;

const UsersSelect = props => {
  const {
    positionsOfSelected: listOfSelectedPositions,
    setpositionsOfSelected: setlistOfSelectedPositions
  } = props;
  const [listOfPositions, setlistOfPositions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [spinLoading, setspinLoading] = useState(true);
  const [orgTreeData, setorgTreeData] = useState([]);

  useEffect(() => {
    getOrgTree();
    return () => {};
  }, []);

  function getOrgTree() {
    get4AChildOrgByParentOrgId().then(res => {
      setorgTreeData(
        res.datas.map(d => ({ ...d, title: d.orgName, key: d.orgId }))
      );
      setspinLoading(false);
    });
  }
  /* eslint no-param-reassign: ["error", { "props": false }] */
  const onLoadData = treeNode =>
    new Promise(resolve => {
      if (treeNode.props.children && treeNode.props.children.length > 0) {
        resolve();
        return;
      }
      get4AChildOrgByParentOrgId({ parentOrgId: treeNode.props.eventKey }).then(
        res => {
          const { datas, errCode, errMsg } = res;
          if (errCode === 0) {
            treeNode.props.dataRef.children = datas.map(d => ({
              ...d,
              key: d.orgId,
              title: d.orgName
            }));
            setorgTreeData([...orgTreeData]);
          } else {
            message.error(errMsg);
          }
          resolve();
        }
      );
    });
  // 树节点选中项变更事件 key:resourceId
  function onOrgTreeSelect(key, { selected }) {
    if (!selected) {
      setlistOfPositions([]);
      return;
    }
    setLoading(true);
    // 获取组织对应岗位用于展示、
    get4APositionByOrgId(key).then(res => {
      const { datas, errCode, errMsg } = res;
      if (errCode === 0) {
        setlistOfPositions(datas);
      } else {
        message.error(errMsg);
      }
      setLoading(false);
    });
  }
  // 已选中组织删除事件
  const onTagDel = key => {
    // 更新tag列表
    setlistOfSelectedPositions(
      listOfSelectedPositions.filter(o => o.id !== key)
    );
  };
  // 渲染树子节点
  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} dataRef={item} />;
    });

  // 子组织表格column
  const orgColumn = [
    { dataIndex: "orgId", title: "组织ID" },
    { dataIndex: "orgName", title: "组织名称" },
    { dataIndex: "id", title: "岗位ID" },
    { dataIndex: "name", title: "岗位名称" }
  ];
  const rowSelection = {
    selectedRowKeys: listOfSelectedPositions.map(o => +o.id),
    onSelect: (record, selected) => {
      if (selected) {
        setlistOfSelectedPositions(listOfSelectedPositions.concat([record]));
      } else {
        setlistOfSelectedPositions(
          listOfSelectedPositions.filter(o => +o.id !== record.id)
        );
      }
    }
  };
  
  return (
    <div className={styles.root}>
      <Spin spinning={spinLoading}>
        <div className={styles.section}>
          <div
            style={{
              width: 230,
              display: "flex",
              flexFlow: "column"
            }}
          >
            <div>组织信息</div>
            <Tree
              loadData={onLoadData}
              onSelect={onOrgTreeSelect}
              className={styles.orgTree}
            >
              {renderTreeNodes(orgTreeData)}
            </Tree>
          </div>
          <div style={{ flex: 1 }}>
            <div>组织岗位信息</div>
            <div className={styles.menuTable}>
              <Table
                rowKey="id"
                columns={orgColumn}
                dataSource={listOfPositions}
                rowSelection={rowSelection}
                pagination={{
                  pageSize: 5
                }}
                loading={loading}
              />
            </div>
          </div>
        </div>
      </Spin>
      <div style={{ padding: "16px 0px" }}>已选：</div>
      <div className={styles.selectedBox}>
        {listOfSelectedPositions.map(rec => (
          <Tag
            style={{ marginBottom: 5 }}
            key={rec.id}
            closable
            onClose={() => onTagDel(rec.id)}
          >
            （{rec.id}）{rec.name}
          </Tag>
        ))}
      </div>
    </div>
  );
};

export default UsersSelect;
